import os
import json
import logging
from typing import Dict, Any

from voice_assistant.event_system import event_system, Events

logger = logging.getLogger("ConfigManager")

class ConfigManager:
    """配置管理器 - 统一管理应用程序配置
    
    特性:
    - 支持从文件加载配置
    - 支持配置覆盖
    - 支持配置持久化
    - 提供默认配置
    """
    
    # 默认配置
    DEFAULT_CONFIG = {
        "app": {
            "name": "语音助手",
            "version": "1.0.0",
            "debug": False,
        },
        "wake_words": ["小爱", "siri", "小艺"],
        "audio": {
            "sample_rate": 16000,
            "channels": 1,
            "chunk_size": 1024,
            "silence_threshold": 1000,
            "max_silence_frames": 160  # 10秒静音
        },
        "server": {
            "ws_url": "ws://localhost:8765",
            "flask_url": "http://localhost:5000",
            "reconnect_base_delay": 1.0,
            "max_reconnect_delay": 60.0
        },
        "ai": {
            "model": "gemma3:4b",
            "url": "http://localhost:11434",
            "prompt_cmd": "你是一个高级 Windows 系统助手，负责将用户指令转化为可执行操作：",
            "params": {
                "temperature": 0.7,
                "top_p": 0.8,
                "top_k": 40,
                "num_predict": 256,
                "num_ctx": 2048,
                "num_gpu": 35,
                "num_thread": 10,
                "stop": ["\\nUser:", "\\n\\n", "</response>"]
            }
        },
        "ui": {
            "always_on_top": True,
            "opacity": 0.9,
            "theme": "light"
        }
    }
    
    def __init__(self):
        self.config = self.DEFAULT_CONFIG.copy()
        self.config_file = os.path.join(os.path.dirname(__file__), "config.json")
    
    def load(self) -> bool:
        """从配置文件加载配置"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    user_config = json.load(f)
                    # 递归更新配置
                    self._update_dict(self.config, user_config)
                logger.info(f"已从 {self.config_file} 加载配置")
                return True
            else:
                logger.info(f"配置文件 {self.config_file} 不存在，使用默认配置")
                # 创建默认配置文件
                self.save()
                return False
        except Exception as e:
            logger.error(f"加载配置文件失败: {str(e)}")
            return False
    
    def save(self) -> bool:
        """保存配置到文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=4)
            logger.info(f"配置已保存到 {self.config_file}")
            
            # 发布配置更改事件
            event_system.publish(Events.CONFIG_CHANGED, {"config": self.config})
            
            return True
        except Exception as e:
            logger.error(f"保存配置文件失败: {str(e)}")
            return False
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项，支持点分隔的路径访问，如 'server.ws_url'"""
        parts = key.split('.')
        value = self.config
        
        try:
            for part in parts:
                value = value[part]
            return value
        except (KeyError, TypeError):
            # 尝试从 DEFAULT_CONFIG 中获取默认值
            try:
                default_value = self.DEFAULT_CONFIG
                for part in parts:
                    default_value = default_value[part]
                return default_value
            except (KeyError, TypeError):
                # 如果 DEFAULT_CONFIG 中也没有，则使用传入的默认值
                return default
    
    def set(self, key: str, value: Any) -> None:
        """设置配置项，支持点分隔的路径访问"""
        parts = key.split('.')
        config = self.config
        
        # 遍历路径直到最后一个部分
        for i, part in enumerate(parts[:-1]):
            if part not in config or not isinstance(config[part], dict):
                config[part] = {}
            config = config[part]
        
        # 设置最后一个部分的值
        config[parts[-1]] = value
    
    def _update_dict(self, target: Dict, source: Dict) -> None:
        """递归更新字典"""
        for key, value in source.items():
            if key in target and isinstance(target[key], dict) and isinstance(value, dict):
                self._update_dict(target[key], value)
            else:
                target[key] = value

# 全局配置管理器实例
config_manager = ConfigManager()